package com.web.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
	Logger log = LogManager.getLogger();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("进入拦截器" + request.getServletPath());
		System.out.println("我证明用户没有登录");
		if (request.getServletPath().contains("login")) {
			log.info("用户访问登录界面");
			return true;
		}
		log.info("验证用户登录信息");
		if (request.getServletPath().contains("doLogin")) {
			log.info("用户访问登录请求");
			return true;
		}
		HttpSession session = request.getSession(true);
		// 请注意自己在session中注册的用户信息变量是否为admin
		if (null == session.getAttribute("Admin")) {
			log.info("session已经过期或者未登录，直接返回登录页面，重新登录");
			response.sendRedirect(request.getContextPath() + "/admin/login");
			return false;
		} else {
			log.info("session认证通过，允许访问");
			return true;
		}
	}

	/**
	 * 生成视图时执行，可以用来处理异常，并记录在日志中
	 */
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2,
			Exception exception) {
		// -----------------//
	}

	/**
	 * - 生成视图之前执行，可以修改ModelAndView
	 */
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {
		// ----------------------------//
	}

	public void test() {
	}
}